package com.sgb.kjwl.viewmodel.transport;

import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.MeManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.DriverInfo;
import com.sgb.kjwl.model.entity.GoodsOrderEntity;
import com.sgb.kjwl.model.entity.self.GoodsSourceDetail;
import com.sgb.kjwl.model.entity.self.UserAccount;
import com.sgb.kjwl.model.entity.shopping.PayCardEntity;
import com.sgb.kjwl.model.entity.transport.GoodsSourcePlace;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.EntityConversion;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.utils.AddressHelper;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 杨畔
 * @date: 2021/2/6 10:41
 * @Description: 竞价货源报价viewModel
 */
public class CargoQuotationViewModel extends AndroidViewModel {
    public MutableLiveData<GoodsSourceDetail> ldCargo = new MutableLiveData<>();
    public MutableLiveData<List<CarInfo>> ldCar = new MutableLiveData<>();
    public MutableLiveData<AMapAddressEntity> ldLocation = new MutableLiveData<>();
    public MutableLiveData<DriverInfo> ldDriverInfo = new MutableLiveData<>();
    public MutableLiveData<PayCardEntity> ldCard = new MutableLiveData<>();
    public MutableLiveData<String> ldTradeNo = new MutableLiveData<>();
    //报价数据
    public MutableLiveData<GoodsOrderEntity> ldQuotation = new MutableLiveData<>();
    public MutableLiveData<String> uploadImgSuccess = new MutableLiveData<>();

    public CargoQuotationViewModel(@NonNull Application application) {
        super(application);
        ldQuotation.setValue(new GoodsOrderEntity());
    }

    /**
     * 待提交提交数据
     */
    public GoodsOrderEntity submitData() {
        if (ldQuotation.getValue() == null) {
            ldQuotation.setValue(new GoodsOrderEntity());
        }
        return ldQuotation.getValue();
    }

    /**
     * 获取货源详情
     */
    public void getDetail(Context context, String no,boolean isDriver) {
        submitData().setGoodsSourceNo(no);
        DialogHelper.showProgressDialog(context, "请求中...");
        String isLogin = UserOperating.getInstance().isLogged() ? "true" : "false";
        NewAPIManager.getInstance().getLogisticsAPI().getGoodsSourceDetail(isLogin, no,null).enqueue(new ICallBack<BaseEntity<GoodsSourceDetail>>() {
            @Override
            public void onSuccess(BaseEntity<GoodsSourceDetail> data) {
                ldCargo.postValue(data.getData());
                //获取支付卡信息
                if (isDriver){
                    getQuickBankList();
                }
            }
        });
    }

    /**
     * 获取快捷支付卡列表
     */
    public void getQuickBankList() {
        MeManager.getInstance().getMaterialAPI().getQuick().enqueue(new ICallBack<BaseEntity<List<PayCardEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PayCardEntity>> data) {
                if (data.getData() != null && data.getData().size() > 0) {
                    ldCard.postValue(data.getData().get(0));
                }
            }

            @Override
            public void onFinally() {
                super.onFinally();
                //获取司机信息
                getDriverInfo();
            }
        });
    }

    /**
     * 获取司机信息
     */
    public void getDriverInfo() {
        NewAPIManager.getInstance().getLogisticsAPI().getDriverInfo().enqueue(new ICallBack<BaseEntity<DriverInfo>>() {
            @Override
            public void onSuccess(BaseEntity<DriverInfo> data) {
                ldDriverInfo.postValue(data.getData());
            }
        });
    }

    /**
     * 获取车辆信息
     */
    public void getCarInfo(Context context) {
        DialogHelper.showProgressDialog(context, "请求中...");
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new ICallBack<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarInfo>> data) {
                ldCar.postValue(data.getData());
            }
        });
    }

    /**
     * 获取定位信息
     */
    public void getCurrentLocation(Context context) {
        AddressHelper.getInstance().getCurrentLocation(context, entity -> {
            if (entity != null) {
                ldLocation.postValue(entity);
            }
        });
    }

    /**
     * 设置货源tag
     */
    public void syncTag(List<String> list, GoodsSourceDetail data) {
        list.clear();
        //货物信息
        StringBuilder builder = new StringBuilder();
        if (!TextUtils.isEmpty(data.getGoodsTypeName())) {
            builder.append(data.getGoodsTypeName());
        }
        if (!TextUtils.isEmpty(data.getSecondGoodsTypeName())){
            builder.append(TextUtils.isEmpty(data.getGoodsTypeName())?data.getSecondGoodsTypeName():"/"+data.getSecondGoodsTypeName());
        }
        list.add(builder.toString());
        if (!TextUtils.isEmpty(data.getAllFreight())) {
            list.add(String.format("%s%s", NumberUtil.trim0(data.getAllFreight()), "元"));
        }
        if (!TextUtils.isEmpty(data.getWeight())) {
            list.add(String.format("%s吨", NumberUtil.trim0(data.getWeight())));
        }
        if (!TextUtils.isEmpty(data.getVolume())) {
            list.add(String.format("%s方", NumberUtil.trim0(data.getVolume())));
        }
        //去除2.0.8
//        if (!TextUtils.isEmpty(data.getPackingModeName())) {
//            list.add(data.getPackingModeName());
//        }
    }

    public String getFreightUnit(Integer freightUnit) {
        String str = "";
        if (freightUnit != null) {
            if (freightUnit == 1) {
                str = "元/趟";
            } else if (freightUnit == 2) {
                str = "元/吨";
            } else if (freightUnit == 3) {
                str = "元/方";
            }
        }
        return str;
    }

    /**
     * 设置货源信息
     */
    public void syncGoodsInfo(List<SingleItemEntity> list, GoodsSourceDetail data) {
        list.clear();
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "包装方式", TextUtils.isEmpty(data.getPackingModeName()) ? "无" : data.getPackingModeName()));
        GoodsSourcePlace place;
        if (data.getPlace() == null) {
            place = EntityConversion.modelA2B(data, GoodsSourcePlace.class);
        } else {
            place = data.getPlace();
        }
        if ("11".equals(data.getHandleTypeNo())) {//一装一卸
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地", place.getProvinceName() + place.getCityName() + place.getDistrictName() + place.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地", place.getDestProvinceName() + place.getDestCityName() + place.getDestDistrictName() + place.getDestDetailAddress()));
        } else if ("12".equals(data.getHandleTypeNo())) {//一装两卸
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地", place.getProvinceName() + place.getCityName() + place.getDistrictName() + place.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地1", place.getViaDestProvinceName() + place.getViaDestCityName() + place.getViaDestDistrictName() + place.getViaDestDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地2", place.getDestProvinceName() + place.getDestCityName() + place.getDestDistrictName() + place.getDestDetailAddress()));
        } else if ("21".equals(data.getHandleTypeNo())) {//两装一卸
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地1", place.getProvinceName() + place.getCityName() + place.getDistrictName() + place.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地2", place.getViaSendProvinceName() + place.getViaSendCityName() + place.getViaSendDistrictName() + place.getViaSendDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地", place.getDestProvinceName() + place.getDestCityName() + place.getDestDistrictName() + place.getDestDetailAddress()));
        } else if ("22".equals(data.getHandleTypeNo())) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地1", place.getProvinceName() + place.getCityName() + place.getDistrictName() + place.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地2", place.getViaSendProvinceName() + place.getViaSendCityName() + place.getViaSendDistrictName() + place.getViaSendDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地1", place.getViaDestProvinceName() + place.getViaDestCityName() + place.getViaDestDistrictName() + place.getViaDestDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地2", place.getDestProvinceName() + place.getDestCityName() + place.getDestDistrictName() + place.getDestDetailAddress()));
        }

        list.add(new SingleItemEntity(SingleItemConstant.TYPE_FOUR));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装车要求", TextUtils.isEmpty(data.getLoadRequire()) ? "/" : data.getloadRequireWords()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸车要求", TextUtils.isEmpty(data.getUnloadRequire()) ? "/" : data.getUnloadRequireWords()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装车时间", data.getShipmentTime()==null||data.getShipmentEndTime()==null?"/":DateUtils.stampToDay5(data.getShipmentTime() + "") + "-" + DateUtils.stampToDay5(data.getShipmentEndTime() + "")));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "到货时间", data.getArrivalTime() == null ? "/" : "自装货结束日期" + data.getArrivalTime() + "天内"));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "付款方式", TextUtils.isEmpty(data.getPayType()) ? "/" : data.getPayType()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "收款账户要求", TextUtils.isEmpty(data.getOtherPaymentRequire()) ? "/" : data.getOtherPaymentRequire()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "发票要求", TextUtils.isEmpty(data.getInvoice()) ? "/" : data.getInvoiceWords()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "税率", TextUtils.isEmpty(data.getTariff()) ? "/" : NumberUtil.trim0(data.getTariff()) + "%"));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "货物损坏/丢失赔偿约定", TextUtils.isEmpty(data.getLostPromise()) ? "/" : data.getLostPromise()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_TWO, "履约保证金", TextUtils.isEmpty(data.getPerformanceBond()) ? "/" : NumberUtil.trim0(data.getPerformanceBond()) + "元", Color.parseColor("#FF6600")));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_TWO, "信息费", data.getMessagePrice()==null?"/":NumberUtil.trim0(data.getMessagePrice()) + "元", Color.parseColor("#FF6600")));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "逾期装货或到货违约责任约定", TextUtils.isEmpty(data.getOverduePromise()) ? "/" : data.getOverduePromise()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "其他约定", TextUtils.isEmpty(data.getOverduePromise()) ? "/" : data.getOverduePromise()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_FOUR));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "发货单位", TextUtils.isEmpty(data.getSendGoodsUnit()) ? "/" : data.getSendGoodsUnit()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系人", TextUtils.isEmpty(data.getSendPeople()) ? "/" : StringUtil.goneName(data.getSendPeople())));
        if (TextUtils.isEmpty(data.getReceptionPhone())) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系电话", "/"));
        } else {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_THREE, "联系电话", TextUtils.isEmpty(data.getSendPhone()) ? "/" : data.getSendPhone()));
        }
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_FOUR));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "收货单位", TextUtils.isEmpty(data.getReceiveGoodsUnit()) ? "/" : data.getReceiveGoodsUnit()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系人", TextUtils.isEmpty(data.getReceptionPeople()) ? "/" : StringUtil.goneName(data.getReceptionPeople())));
        if (TextUtils.isEmpty(data.getReceptionPhone())) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系电话", "/"));
        } else {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_THREE, "联系电话", data.getReceptionPhone()));
        }

    }

    /**
     * 设置司机信息
     */
    public void syncDriverInfo(List<SingleItemEntity> list, DriverInfo info) {
        GoodsSourceDetail goods = ldCargo.getValue();
        PayCardEntity card = ldCard.getValue();
        list.clear();
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "可装车时间", String.format("%s-%s",
                goods.getShipmentTime()==null?"/":DateUtils.stampToDay5(goods.getShipmentTime() + ""),
                goods.getShipmentEndTime()==null?"/":DateUtils.stampToDay5(goods.getShipmentEndTime() + ""))));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "司机姓名", TextUtils.isEmpty(info.getName()) ? "/" : info.getName()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系电话", TextUtils.isEmpty(info.getTelphone()) ? "/" : info.getTelphone()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "年龄", TextUtils.isEmpty(info.getCarAge()) ? "/" : info.getCarAge()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "驾龄", TextUtils.isEmpty(info.getDriverAge()) ? "/" : info.getDriverAge()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "收款账户", card == null || TextUtils.isEmpty(card.openingBank) ? "/" : card.openingBank));
    }

    /**
     * 报价（条件判断）
     */
    public void quotation(Context context) {
        //判断是否是第一次支付
//        isFirstPay(context);
        realQuotation(context);

    }

    /**
     * 判断用户第一次接单支付
     */
    private void isFirstPay(Context context) {
        DialogHelper.showProgressDialog(context, "加载中");
        APIManager.getInstance().getDriverAPI().isFirstPay().enqueue(new ICallBack<BaseEntity<UserAccount>>() {
            @Override
            public void onSuccess(BaseEntity<UserAccount> data) {
                if (data.getData().isFirstPay()) {
                    showFirstPayDialog(context);
                } else {
                    realQuotation(context);
                }
            }
        });
    }

    /**
     * 第一次支付弹窗
     */
    public void showFirstPayDialog(Context context) {
        View view = View.inflate(context, R.layout.dialog_order_rules, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(context, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        ImageView img_cancel = view.findViewById(R.id.img_cancel);
        ConstraintLayout rl_content = view.findViewById(R.id.rl_content);
        tv_sure.setVisibility(View.VISIBLE);
        rl_content.setBackgroundResource(R.drawable.shape_circle_corner_white_half_5dp);
        //确定
        tv_sure.setOnClickListener(v -> {
            realQuotation(context);
            roundCornerDialog.dismiss();
        });
        //取消
        img_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    /**
     * 实际报价接口
     */
    private void realQuotation(Context context) {
        DialogHelper.showProgressDialog(context, "加载中");
        NewAPIManager.getInstance().getLogisticsAPI().goodsBiddingOffer(submitData()).enqueue(new Callback<BaseEntity<String>>() {
            @Override
            public void onResponse(Call<BaseEntity<String>> call, Response<BaseEntity<String>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getCode() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK) && response.body().getCode().equals("200")) {
                    if (response.body().getData() != null && !TextUtils.isEmpty(response.body().getData())) {
                        //报价成功
                        if (!TextUtils.isEmpty(response.body().getData())) {
                            ldTradeNo.postValue(response.body().getData());
                        }
                    }
                } else {
                    ToastUtil.show(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<String>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.show(context,t.getMessage());
            }
        });
    }
    //上传多图片
    public void uploadMutiFileModels(Context context, List<File> files) {
        Map<String, RequestBody> photos = new HashMap<>();
        List<RequestBody> list = new ArrayList<>();
        int i = 0;
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            photos.put("file" +i+ "\"; filename=\"" + i + "image.jpg\"", requestBody);
            i++;
        }
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUploadAPI().uploadMutiFileDrive(photos).enqueue(new Callback<BaseEntity<List<String>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<String>>> call, Response<BaseEntity<List<String>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || TextUtils.isEmpty(response.body().getState())) {
                    DialogHelper.dismissProgressDialog();
                    MToast.showLongToast(context, "上传失败");
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData()!=null) {
                        StringBuffer s = new StringBuffer();
                        List list1= response.body().getData();
                        for (int i1 = 0; i1 < list1.size(); i1 ++) {
                            if (i1 == list1.size() - 1) {
                                s.append(list1.get(i1));
                            } else {
                                s.append(list1.get(i1) + ",");
                            }
                        }
                        uploadImgSuccess.postValue(s.toString());
                    } else {
                        DialogHelper.dismissProgressDialog();
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<String>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(context, t.getMessage());
            }
        });
    }
}
